<?php
// +----------------------------------------------------------------------
// | Description: 保有
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\shop\model\Order as OrderModel;
use app\admin\model\ShopModel;
use think\facade\Db;
use app\Request;
use think\Env;
use OSS\OssClient;
use OSS\Core\OssException;

class ServiceRun
{
    // public function __construct()
    // {
    //     $this->accessKeyId     = env('FILESYSTEM.aliyun_access_id');
    //     $this->accessKeySecret     = env('FILESYSTEM.aliyun_access_secret');
    //     $this->endpoint     = env('FILESYSTEM.aliyun_endpoint');
    //     $this->bucket = env('FILESYSTEM.aliyun_bucket');
    //     $this->url = env('FILESYSTEM.aliyun_url');
    // }
    
    

    // public function pingyang()
    // {
    //     $result = Db::name('service')->field('s.id, c.customer_name, c.telephone, c.king_no, s.name, s.service_type, s.num, s.start_time, s.end_time, s.kk_money')
    //         ->alias('s')
    //         ->leftJoin('customer c', 's.customer_id = c.id')
    //         ->where('s.shop_id',73782775013838)
    //         ->where('s.kk_money',0)
    //         // ->limit(0,500)
    //         ->select()
    //         ->toArray();
    //     foreach($result as  &$v)
    //     {
    //         //查询次数
    //         if($v['service_type'] == 2)
    //         {
    //             $count = Db::name('service_log')->where('service_id',$v['id'])->count();
    //             $v['count'] = $v['num'] - $count;
    //         }else
    //         {
    //             $v['count'] = '';
    //         }
    //         $v['service_type'] = $v["service_type"] === 1 ? '疗程卡' : '次卡';
    //         $v["start_time"] = $v["start_time"] === 0 ? '' : date('Y-m-d', $v["start_time"]);
    //         $v["end_time"] = $v["end_time"] === 0 ? '' : date('Y-m-d', $v["end_time"]);
    //     }
        
    //     $callName = [
    //             'customer_name' => '姓名',
    //             'telephone' => '手机号',
    //             'king_no' => '金蝶编码',
    //             'name' => '开卡名称',
    //             'kk_money' => '开卡金额',
    //             'service_type' => '卡项类型',
    //             'num' => '开卡次数',
    //             'count' => '剩余次数',
    //             'start_time' => '开卡开始时间',
    //             'end_time' => '开卡结束时间',
    //         ];
    
    //     $downUrl = exportExcelData('中街店',$callName,$result,'xlsx',1);

    //     echo "<script language='javascript'>";

    //     echo " location='".$downUrl."';";

    //     echo "</script>";
        
    //     die;
    // }
    
    public function goodsDaochu()
    {
        $kingdeeCodes = [
            // "101.12.072",
            // "101.12.049",
            // "101.12.027",
            // "101.12.028",
            // "101.12.024",
            // "101.12.032",
            // "101.12.004",
            // "101.12.005",
            // "101.12.006",
            // "101.12.007",
            // "101.12.008",
            // "101.12.009", 
            // "101.12.010",
            // "101.12.012",
            // "101.12.017",
            // "101.12.018",
            // "101.12.025",
            // "101.12.038",
            // "101.12.039",
            // "101.12.041",
            // "105.12.097",
            // "101.12.064",
            // "101.03.001",
            // "101.03.003",
            // "101.03.004",
            // "101.03.005",
            // "101.03.008",
            // "101.03.009",
            // "101.04.015",
            // "101.04.016",
            // "101.04.017",
            // "101.02.008",
            // "101.04.019",
            // "101.03.010",
            // "101.02.010",
            // "101.02.009",
            // "101.04.020",
            // "101.02.011",
            // "101.02.012",
            // "101.02.013",
            // "101.03.011",
            // "101.03.012",
            // "101.04.021",
            // "101.02.014",
            // "101.05.013",
            // "101.33.004",
            // "101.05.014",
            // "101.05.015",
            // "101.05.016",
            // "101.05.017",
            // "101.05.018",
            // "101.04.022",
            // "101.04.024",
            // "101.04.025",
            // "101.04.026",
            // "101.04.027",
            // "101.03.013",
            // "101.05.037",
            // "101.12.034",
            "101.12.070",
        ];
        // var_dump($kingdeeCodes);die;
        
        $allResults = [];
        foreach ($kingdeeCodes as $kingdeeCode) {
            $result = Db::name('shop_order_goods')
                ->alias('g')
                ->leftJoin('shop_order o', 'g.order_id = o.id')
                ->field([
                    'g.goods_name',
                    'g.kingdee_code',
                    'o.shop_id',
                    'o.shop_name',
                    'o.uid',
                    Db::raw('g.pay_price * g.number AS pay_price'),
                    'g.create_time'
                ])
                ->where('g.kingdee_code', $kingdeeCode)
                ->where('g.pay_price', '>', 0)
                ->whereBetween('g.create_time', [1735660800, 1743436799])
                ->order('o.uid', 'desc')
                ->select()->toArray();
        
            $allResults = array_merge($allResults, $result);
        }
        // echo "<pre>";
        // print_r($result);die;
        
        $shopData = [];
        foreach ($allResults as $item) {
            $shop_id = $item['shop_id'];
            if (!isset($shopData[$shop_id])) {
                $shopData[$shop_id] = [];
            }
            $shopData[$shop_id][] = $item;
        }
        
        $finalResult = [];
        foreach ($shopData as $shopId => $orders) {
            $firstOrderCount = 0;
            $firstOrderAmount = 0;
            $repurchaseCount = 0;
            $repurchaseAmount = 0;
            $firstOrderTimes = [];
        
            // 找出每个用户的首单时间
            foreach ($orders as $order) {
                $uid = $order['uid'];
                if (!isset($firstOrderTimes[$uid]) || $order['create_time'] < $firstOrderTimes[$uid]) {
                    $firstOrderTimes[$uid] = $order['create_time'];
                }
            }
        
            // 统计首单和复购信息
            foreach ($orders as $order) {
                $uid = $order['uid'];
                if ($order['create_time'] == $firstOrderTimes[$uid]) {
                    $firstOrderCount++;
                    $firstOrderAmount += $order['pay_price'];
                } else {
                    $repurchaseCount++;
                    $repurchaseAmount += $order['pay_price'];
                }
            }
        
            // 提取公共信息
            $firstOrder = reset($orders);
            $finalResult[$shopId] = [
                'goods_name' => $firstOrder['goods_name'],
                'kingdee_code' => $firstOrder['kingdee_code'],
                'shop_name' => $firstOrder['shop_name'],
                'firstOrderCount' => $firstOrderCount,
                'firstOrderAmount' => $firstOrderAmount,
                'repurchaseCount' => $repurchaseCount,
                'repurchaseAmount' => $repurchaseAmount
            ];
        }
        // echo "<pre>";
        // print_r($finalResult);die;
        // echo "</pre>";
    
            
        
        
        $callName = [
                'goods_name' => '商品名称',
                'kingdee_code' => '金蝶编码',
                'shop_name' => '店铺名',
                'firstOrderCount' => '首单次数',
                'firstOrderAmount' => '首单金额',
                'repurchaseCount' => '复购次数',
                'repurchaseAmount' => '复购金额',
            ];
    
        $downUrl = exportExcelData('商品销售',$callName,$finalResult,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }
    
    
    //A客人
    public function AlevelDaoChu()
    {
        $list['data'] = Db::name('customer');
        
        foreach($list['data'] as $key => &$val)
        {
            // 年度消费金额 + 门店消费 + 门诊消费 + 门店贡献
            $amount = $this->yearAmount($val['id'],$val['shop_id'],$today);//查询门店总金额
            $val['year_amount'] = $amount['year_amount']?? 0;
             if ($val['year_amount'] < 50000)
             {
                unset($list['data'][$key]);
            }
            $val['md_amount'] = $amount['md_amount']?? 0;
            $val['mz_amount'] = $amount['mz_amount']?? 0;
            $val['bahen'] = Db::name('customer_scar')
                ->alias('c')
                ->join('setting s', 'c.customer_setting_id_type = s.id')
                ->where('c.customer_id', $val['id'])
                ->value('s.name');
        }
        
        $callName = [
                'customer_name' => '姓名',
                'telephone' => '手机号',
                'source_name' => '来源',
                'bahen' => '疤痕类型',
                'shop_name' => '门店',
                'market_name' => '市场',
                'mz_amount' => '门诊消费金额',
                'md_amount' => '门店消费金额',
                'year_amount' => '年度消费金额',
            ];

        $downUrl = exportExcelData('24.6月--25.3月成交用户数据',$callName,$user,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }
    //24.6 - 25.3 
    public function yearDaochu()
    {
        $today = date('Y-m-d');
        $startTime = '1717171200';
        $endTime = '1743436800';
        $user = Db::name('customer')
            ->alias('c')
            ->join('shop s1', 'c.shop_id = s1.shop_id', 'LEFT')
            ->join('setting s2', 's2.id = c.source_id', 'LEFT')
            ->field('c.id, c.customer_name, c.telephone, c.sex, c.birthday, c.create_time, c.cj_time, c.cj_order_id, c.shop_id, s1.shop_name, s1.market_name, s2.name as source_name')
            ->where('c.cj_money', '>', 0)
            ->where('c.cj_time', 'between', [$startTime, $endTime])
            ->limit(6900, 300)
            ->select()->toArray();
        foreach($user as &$val)
        {
            //查询门店总金额
            $amount = $this->yearAmount($val['id'],$val['shop_id'],$today);
            $val['year_amount'] = $amount['year_amount']?? 0;
             //预存余额查询
            $balanceField = ['SUM(b.money) as money','SUM(b.complimentary_money) as complimentary_money','SUM(b.shop_transfer_money) as shop_transfer_money'];
            $balanceList = Db::name('customer_balance')->alias('b')
                ->join('customer_balance_category c', 'c.id = b.balance_category_id')
                ->where('b.customer_id', '=', $val['id'])
                ->field($balanceField)
                ->group('b.balance_category_id')
                ->select()
                ->toArray();
            $totalAllMoney = 0;
            foreach ($balanceList as &$item)
            {
                $item['all_money'] = bcadd(bcadd($item['money'], $item['complimentary_money'], 2), $item['shop_transfer_money'], 2);
                // 累加总预存金额
                $totalAllMoney = bcadd($totalAllMoney, $item['all_money'], 2);
            }
            $val['yucun'] = $totalAllMoney;
            
            if(!empty($val['cj_order_id']))
            {
                $closest_value = Db::name('shop_refund_order')
                    ->where('id', $val['cj_order_id'])
                    ->value('business_type');
                $val['eeee'] = '有';
            }else
            {
                $shop_order_type = Db::name('shop_refund_order')
                    ->whereIn('uid', $val['id'])
                    ->where('status', 2)
                    ->where('type', 3)
                    ->where('refund_type', '101.02')
                    ->where('pay_amount', '>=', 500)
                    ->column('business_type','create_time');
                    
                $closest_value = null;
                $min_difference = PHP_INT_MAX;
                
                foreach ($shop_order_type as $time => $value)
                {
                    $difference = abs($time - $val['cj_time']);
                    if ($difference < $min_difference)
                    {
                        $min_difference = $difference;
                        $closest_value = $value;
                    }
                }
                $val['eeee'] = '无';
            }
            if($closest_value == 1)
            {
                $val['shoukuan_type'] = '疤痕';
            }elseif($closest_value == 2)
            {
                $val['shoukuan_type'] = '项目';
            }elseif($closest_value == 3)
            {
                $val['shoukuan_type'] = '青春痘';
            }elseif($closest_value == 4)
            {
                $val['shoukuan_type'] = '护肤品';
            }
            
            $order_type = Db::name('shop_order')
                ->whereIn('uid', $val['id'])
                ->where('status', 2)
                ->where('order_type', 1)
                ->where('total_amount', '>=', 500)
                ->order('deal_time')
                ->value('business_type');
            if(!empty($order_type))
            {
                $val['aaaa'] = '新单';
            }else
            {
                $order_type = Db::name('shop_order')
                ->whereIn('uid', $val['id'])
                ->where('status', 2)
                ->where('order_type', 2)
                ->where('total_amount', '>=', 500)
                ->order('deal_time')
                ->value('business_type');
                $val['aaaa'] = '补单';
            }
            if($order_type == 1)
            {
                $val['xiaoshou_type'] = '疤痕';
            }elseif($order_type == 2)
            {
                $val['xiaoshou_type'] = '项目';
            }elseif($order_type == 3)
            {
                $val['xiaoshou_type'] = '青春痘';
            }elseif($order_type == 4)
            {
                $val['xiaoshou_type'] = '护肤品';
            }
            $val['bahen'] = Db::name('customer_scar')
                ->alias('c')
                ->join('setting s', 'c.customer_setting_id_type = s.id')
                ->where('c.customer_id', $val['id'])
                ->value('s.name');
            $val['photo'] = Db::name('customer_album')
                ->alias('c')
                ->join('setting s', 'c.scar_type_id = s.id')
                ->where('c.customer_id', $val['id'])
                ->where('c.is_del', '=', 0)
                ->order('c.create_time')
                ->value('s.name');
            $val['cj_time'] = ($val['cj_time'] != 0) ? (date('Y-m-d', $val['cj_time'])?? '') : "";
            $val['create_time'] = ($val['create_time'] != 0) ? (date('Y-m-d', $val['create_time'])?? '') : "";
            $val['age'] = bcsub(date('Y'),date('Y',$val['birthday']));
            $val['sex'] = $val['sex'] === 1 ? '男' : ($val['sex'] === 2 ? '女' : '未知');
        }
        
        $callName = [
            'customer_name' =>'姓名',
            'telephone' =>'手机号',
            'sex' =>'性别',
            'age' => '年龄',
            'market_name' => '市场',
            'shop_name' => '门店',
            'create_time' => '录入时间',
            'cj_time' => '成交时间',
            'year_amount' => '年度消费金额',
            'yucun' => '预存',
            'source_name' => '来源',
            'shoukuan_type' => '成交类型',
            'eeee' => '有无order_id',
            'xiaoshou_type' => '销售单类型',
            'aaaa' => '新单/补单',
            'bahen' => '疤痕类型',
            'photo' => '照片疤痕类型'
            
        ];

        $downUrl = exportExcelData('24.6月--25.3月成交用户数据',$callName,$user,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
        
    }
    
    public function userDaochu()
    {
        $list = Db::name('customer')
            ->alias('c')
            ->join('shop s', 'c.shop_id = s.shop_id AND s.shop_type = 2 AND s.status = 1')
            ->whereExists(function ($query) {
                $query->table('xy_customer')->alias('c2')
                    ->join('shop s2', 'c2.shop_id = s2.shop_id AND s2.shop_type = 2 AND s2.status = 1')
                    ->whereColumn('c2.telephone', 'c.telephone')
                    ->whereColumn('c2.shop_id', 'c.shop_id') // 确保同一门店
                    ->group('c2.telephone, c2.shop_id')
                    ->having('COUNT(c2.id) > 1');
            })
            ->field('c.id, c.customer_name, c.telephone, c.sex, s.shop_name, c.king_no, c.membership_leve')
            ->order('c.telephone')
            ->select()
            ->toArray();
        foreach($list as &$val)
        {
            $val['sex'] = $val['sex'] === 1 ? '男' : ($val['sex'] === 2 ? '女' : '未知');
            $val['membership_leve'] = $val['membership_leve'] === 1 ? '白玉兰' : ($val['membership_leve'] === 2 ? '紫玉兰' : ($val['membership_leve'] === 3 ? '金玉兰' : ($val['membership_leve'] === 0 ? '暂无' : '暂无')));
            //预存余额查询
            $balanceField = ['SUM(b.money) as money','SUM(b.complimentary_money) as complimentary_money','SUM(b.shop_transfer_money) as shop_transfer_money'];
            $balanceList = Db::name('customer_balance')->alias('b')
                ->join('customer_balance_category c', 'c.id = b.balance_category_id')
                ->where('b.customer_id', '=', $val['id'])
                ->field($balanceField)
                ->group('b.balance_category_id')
                ->select()
                ->toArray();
            $totalAllMoney = 0;
            foreach ($balanceList as &$item)
            {
                $item['all_money'] = bcadd(bcadd($item['money'], $item['complimentary_money'], 2), $item['shop_transfer_money'], 2);
                // 累加总预存金额
                $totalAllMoney = bcadd($totalAllMoney, $item['all_money'], 2);
            }
            $val['yucun'] = $totalAllMoney;
            
            //订单查询
            $chuku = Db::name('shop_order')->where('uid',$val['id'])->where('status',2)->where('total_amount','>',0)->count();
            $shoukuan = Db::name('shop_refund_order')->where('uid',$val['id'])->where('status','>',0)->where('pay_amount','>',0)->count();
            $val['order'] = $chuku + $shoukuan;
            
            //卡项查询
            $val['qika_guoqi'] = Db::name('service')->where('customer_id',$val['id'])->where('service_type',1)->where('end_time','<',time())->where('status','<>',1)->count();
            $val['qika_meiguo'] = Db::name('service')->where('customer_id',$val['id'])->where('service_type',1)->where('end_time','>',time())->where('status',1)->count();
            $val['cika'] = Db::name('service')->where('customer_id',$val['id'])->where('service_type',1)->where('status',1)->count();
        }
        
        // var_dump($list);die;
        
        $callName = [

            'customer_name' =>'客户姓名',
            'telephone' =>'手机号',
            'sex' =>'性别',
            'shop_name' => '门店',
            'membership_leve' => '会员等级',
            'king_no' => 'K3代码',
            'yucun' => '预存',
            'order' => '订单数量',
            'qika_guoqi' => '疗程卡过期数量',
            'qika_meiguo' => '疗程卡没过期数量',
            'cika' => '次卡数量'
            
        ];

        $downUrl = exportExcelData('项目数据',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }
    
    
    
    public function kkDaochu()
    {
        $service = Db::name('service')
            ->alias('s')
            ->join('customer c', 's.customer_id = c.id', 'LEFT')
            ->join('service_log sl', 's.id = sl.service_id', 'LEFT')
            ->join('shop_person sp', 'sl.nurse_id_one = sp.id', 'LEFT')
            ->field('s.id, s.customer_id, s.name, s.num, s.start_time, s.end_time, s.create_time, s.kk_money, c.customer_name, c.telephone, sp.name as nures_name, COUNT(sl.id) as count')
            ->where('kk_money', 0)
            ->group('s.id')
            ->limit(500, 1)
            ->select()
            ->toArray();
        
        foreach ($service as $key => $val)
        {
            $service[$key]['create_time'] = ($val['create_time'] != 0) ? (date('Y-m-d', $val['create_time'])?? '') : "";
            $service[$key]['start_time'] = ($val['start_time'] != 0) ? (date('Y-m-d', $val['start_time'])?? '') : "";
            $service[$key]['end_time'] = ($val['end_time'] != 0) ? (date('Y-m-d', $val['end_time'])?? '') : "";
        }
        var_dump($service);die;
        
        $callName = [

            'customer_name' =>'客户姓名',
            'telephone' =>'手机号',
            'name' => '开卡名称',
            'create_time' => '开卡时间',
            'kk_money' => '开卡金额',
            'num' => '开卡次数',
            'start_time' => '服务开始时间',
            'end_time' => '服务开始时间',
            'count' => '消耗次数',
            'nures_name' => '护理师'
            
        ];

        $downUrl = exportExcelData('项目数据',$callName,$service,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }
    
    /**
     * 上传文件到指定用户目录
     * @param string username 用户名
     * @param string mobile   手机号
     * @param string filePath 本地文件路径
     * @param string|null customName 自定义文件名（可选）
     * @return string 文件访问URL
     */
    public function pushFile(Request $request)
    {
        // 获取普通表单参数
        $param = $request->param();
        // 获取文件上传信息
        $file = $request->file('filePath');
        // var_dump($file);die;
    
        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $param['mobile']))
        {
            return json(['error' => "无效的手机号码格式", 'code' => 0]);
        }
    
        // 生成OSS对象路径  姓名-手机号-YYYYMMDD
        $folderPath = $this->generateFolderPath($param['username'], $param['mobile']);
        // 生成新的对象名，格式为 姓名_手机号_年月日_时分秒
        $objectName = $param['username'] . '_' . $param['mobile'] . '_' . date('Ymd_His') . '.' . $file->getOriginalExtension();
        
        try {
            $ossClient = new OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );
            // 获取临时文件路径
            $filePath = $file->getRealPath();
    
            // 检查文件夹路径是否为空，如果为空，直接使用对象名上传
            if (!empty($folderPath))
            {
                // 组合完整的对象名，包含文件夹路径
                $fullObjectName = $folderPath . '/' . $objectName; 
                $ossClient->uploadFile($this->bucket, $fullObjectName, $filePath);
            }else
            {
                // 如果文件夹路径为空，只使用文件名上传
                $ossClient->uploadFile($this->bucket, $file->getOriginalName(), $filePath);
            }
    
            return $this->getFileUrl($fullObjectName); 
    
        }catch (OssException $e)
        {
            return json(['error' => $e->getMessage(), 'code' => 0]);
        }
    }
    
    /**
     * 获取文件访问URL
     * @param string $objectName OSS对象路径
     * @param int $expire 链接有效期（秒），默认10分钟
     * @return string
     */
    public function getFilesInFolder(Request $request)
    {
        $param = $request->param();
        try 
        {
            $ossClient = new OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );

            // 确保文件夹路径以斜杠结尾
            if (substr($param['path'], -1) !== '/') {
                $param['path'] .= '/';
            }

            // 设置参数
            $options = [
                'prefix' => $param['path'], // 指定前缀为文件夹路径
                'delimiter' => '/' // 分隔符
            ];

            // 调用 listObjects 方法获取文件列表
            $result = $ossClient->listObjects($this->bucket, $options);
            $objects = $result->getObjectList();
            
            $fileList = [];
            foreach ($objects as $object)
            {
                $fileList[] = $ossClient->signUrl($this->bucket, $object->getKey(), 3600);
            }

            return json(['data' => $fileList, 'code' => 1]);

        } catch (OssException $e)
        {
            return json(['error' => $e->getMessage(), 'code' => 0]);
        }
    }

    
    
    /**
     * 生成存储路径
     * @param string $username
     * @param string $mobile
     * @return string 格式：username-mobile-YYYYMMDD
     */
    private function generateFolderPath(string $username, string $mobile): string
    {
        // 过滤特殊字符
        $cleanName = preg_replace('/[^a-zA-Z0-9_\x{4e00}-\x{9fa5}]/u', '', $username);
        $dateStr = date('Ymd');
        
        return "{$cleanName}_{$mobile}_{$dateStr}";
    }

    
    
    public function serviceNumRun()
    {
        // $service = Db::name('service')
        //     ->where('kk_money',0)
        //     ->where('service_type',2)
        //     ->where('status',1)
        //     ->limit(45000,5000)
        //     ->select()
        //     ->toArray();
            // var_dump($service);die;
        foreach($service as $key => $val)
        {
            $update = [];
            if(!empty($val['order_id']))
            {
                // 查询金额
                $order = Db::name('shop_order')
                    ->where('uid',$val['customer_id'])
                    ->where('id',$val['order_id'])
                    ->where('total_amount','>',0)
                    ->value('id');
            }else
            {
                //服务（各类疗程卡项及疗程卡项赠送产品）
                $order = Db::name('shop_order')
                    ->where('uid',$val['customer_id'])
                    ->where('income_type',1) 
                    ->where('create_time',$val['create_time'])
                    ->where('total_amount','>',0)
                    ->value('id');
            }
            //查询二级订单销售金额
            if(!empty($order))
            {
                $price = Db::name('shop_order_goods')
                ->where('order_id',$order)
                ->where('goods_id',$val['goods_id'])
                ->where('pay_price','>',0)
                ->sum('pay_price');
                //赋值
                if(!empty($price))
                {
                    $update['kk_money'] = $price;
                    $update['consume_money'] = $price;
                }
            }
            if(!empty($update))
            {
                var_dump($val['id']);
                var_dump($update);
                Db::name('service')->where('id',$val['id'])->update($update);
                $services = Db::name('service')->where('id',$val['id'])->select()->toArray();
                $this->serviceLogRun($services);
            }
        }
        echo "success";
        die;
    }
    
    
    
    public function serviceLogRun($service)
    {
        // var_dump($service);die;
        // $service = Db::table('xy_service')
        // ->where('kk_money', '>', 0)
        // ->where('consume_gratuity', '=', 0)
        // ->where('consume_money', '=', 0)
        // ->where('consume_store_transfer', '=', 0)
        // ->limit(0, 5000)
        // // ->where('id','=',23501)
        // ->select()
        // ->toArray();
        // $service = [];
        // 数据纠正
        foreach($service as $key => $val)
        {
            //判断有无LOG
            $val['log'] = Db::name('service_log')
                ->alias('sl')
                ->join('shop_goods sg', 'sl.goods_id = sg.id')
                ->field(['sl.*','sg.month_allowed_entry_max as month','sg.halfmonth_allowed_entry_max as half'])
                ->where('sl.service_id', $val['id'])
                ->where('sl.is_cancel','<>',2)//未作废
                ->select()
                ->toArray();
            //进行数据处理
            if (!empty($val['log']))
            {
                $monthlyCount = [];
                $count = 0; // 次数
                foreach ($val['log'] as $kk => $lv)// log数据
                { 
                    $updateLog = [];
                    $updateNum = [];
                    if ($val['service_type'] == 1) // 按期
                    {
                        $count++;
                        // 如果商品没有次数限制
                        if ($lv['month'] < 1 && $lv['half'] < 1)
                        {
                            if ($val['status'] != 1) // 已结束
                            {
                                if ($count == count($val['log']))
                                {
                                    // 最后一次分配时，将剩余金额全部分配给它
                                    $remaining_money = bcsub($val['kk_money'], bcmul(bcdiv($val['kk_money'], count($val['log']), 2), $count - 1, 2), 2);
                                    $updateLog['consume_money'] = $remaining_money;
                                } else {
                                    $updateLog['consume_money'] = bcdiv($val['kk_money'], count($val['log']), 2);
                                }
                            }
                        }else
                        {
                            // 如果没有进店次数
                            if ($val['first_month_max_service_num'] < 1 && $val['middle_month_max_service_num'] < 1 && $val['end_month_max_service_num'] < 1)
                            {
                                // 计算
                                $enterShopData = $this->getOrderModel()->getMaxCustomerEnterShop($val['start_time'], $val['end_time'], $lv['half'], $lv['month']);
            
                                $updateNum['service_max_num'] = bcmul($enterShopData['service_max_num'], 1, 2);
                                $updateNum['first_month_max_service_num'] = $enterShopData['shou'];
                                $updateNum['middle_month_max_service_num'] = $enterShopData['zhong'];
                                $updateNum['end_month_max_service_num'] = $enterShopData['wei'];
            
                                Db::name('service')->where('id', $val['id'])->update($updateNum);
                            }
            
                            // 计算最大次数
                            $val['create_time'] = $lv['create_time'];
                            $maxNum = $this->getMonthEnterShopNum($val);
            
                            // 获取当前记录的年月
                            $currentMonth = date('Y-m', $lv['create_time']);
                            // 如果该月的统计次数还未初始化，则初始化为 0
                            if (!isset($monthlyCount[$currentMonth]))
                            {
                                $monthlyCount[$currentMonth] = 0;
                            }
            
                            // 增加该月的统计次数
                            $monthlyCount[$currentMonth]++;
            
                            if ($monthlyCount[$currentMonth] <= $maxNum)
                            {
                                $updateLog['consume_money'] = $maxNum > 0 ? bcdiv($val['kk_money'], $maxNum, 2) : 0;
                            }else
                            {
                                $updateLog['consume_money'] = 0;
                            }
                        }
                    }elseif($val['service_type'] == 2) // 按次
                    {
                        $count++;
                        // 如果核销次数大于存卡次数
                        if (count($val['log']) > $val['num'])
                        {
                            if ($count <= $val['num'])
                            {
                                if ($count == $val['num'])
                                {
                                    // 最后一次非零分配时，将剩余金额全部分配给它
                                    $remaining_money = bcsub($val['kk_money'], bcmul(bcdiv($val['kk_money'], $val['num'], 2), $count - 1, 2), 2);
                                    $updateLog['consume_money'] = $remaining_money;
                                }else
                                {
                                    $updateLog['consume_money'] = bcdiv($val['kk_money'], $val['num'], 2);
                                }
                            }else
                            {
                                $updateLog['consume_money'] = 0;
                            }
                        // 如果核销次数小于卡次数
                        }elseif(count($val['log']) < $val['num'])
                        {
                            if ($val['status'] == 1) // 未结束
                            {
                                $updateLog['consume_money'] = bcdiv($val['kk_money'], $val['num'], 2);
                            }else
                            {
                                if ($count == count($val['log']))
                                {
                                    // 最后一次分配时，将剩余金额全部分配给它
                                    $remaining_money = bcsub($val['kk_money'], bcmul(bcdiv($val['kk_money'], $val['num'], 2), $count - 1, 2), 2);
                                    $updateLog['consume_money'] = $remaining_money;
                                }else
                                {
                                    $updateLog['consume_money'] = bcdiv($val['kk_money'], $val['num'], 2);
                                }
                            }
                        // 如果核销次数等于卡次数
                        }elseif(count($val['log']) == $val['num'])
                        {
                            if ($count == count($val['log']))
                            {
                                // 最后一次分配时，将剩余金额全部分配给它
                                $remaining_money = bcsub($val['kk_money'], bcmul(bcdiv($val['kk_money'], $val['num'], 2), $count - 1, 2), 2);
                                $updateLog['consume_money'] = $remaining_money;
                            }else
                            {
                                $updateLog['consume_money'] = bcdiv($val['kk_money'], $val['num'], 2);
                            }
                        }
                        
                    }
                    // 执行修改
                    Db::name('service_log')->where('id', $lv['id'])->update($updateLog);
                }
            }
            // $updateService = [];
            // $updateService['consume_money'] = $val['kk_money'];
            //修改service的消耗本金
            // Db::name('service')->where('id',$val['id'])->update($updateService);
        }
        // echo "success";
        // die;
    }
    
    
    
    public function getMonthEnterShopNum($serviceData)
    {
        $cancel_time = $serviceData['create_time'];
        //核销的年份
        $year_cancel = date('Y',$cancel_time);
        //核销的月份
        $month_cancel = date('m',$cancel_time);
        $yearMonthCancel = date('Ym',$cancel_time);
        //服务开始时间
        $service_begin_time = $serviceData['start_time'];
        $service_begin_time_year = date('Y',$service_begin_time);
        $service_begin_time_month = date('m',$service_begin_time);
        $service_begin_time_yearMonth = date('Ym',$service_begin_time);

        //服务结束时间
        $service_end_time = $serviceData['end_time'];
        $service_end_time_year = date('Y',$service_end_time);
        $service_end_time_month = date('m',$service_end_time);
        $service_end_time_yearMonth = date('Ym',$service_end_time);

        // 同年同月
        if($service_begin_time_yearMonth == $service_end_time_yearMonth )
        {

            $max_cancel_num = $serviceData['first_month_max_service_num'];
        }else
        {

            if($service_begin_time_year == $service_end_time_year)
            {

                //同年
                if($month_cancel ==$service_begin_time_month )
                {
                    $max_cancel_num = $serviceData['first_month_max_service_num'];
                }elseif($month_cancel == $service_end_time_month)
                {
                    $max_cancel_num = $serviceData['end_month_max_service_num'];
                }else
                {
                    $max_cancel_num = $serviceData['middle_month_max_service_num'];
                }
            }else
            {

                //跨年
                if($year_cancel == $service_begin_time_year)
                {

                    if($month_cancel == $service_begin_time_month)
                    {

                        $max_cancel_num = $serviceData['first_month_max_service_num'];
                    }else
                    {

                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }
                }elseif($year_cancel == $service_end_time_year)
                {

                    if($month_cancel == $service_end_time_month)
                    {

                        $max_cancel_num = $serviceData['end_month_max_service_num'];
                    }else
                    {

                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }
                }else
                {
                    if($month_cancel == 1)
                    {
                        $max_cancel_num = $serviceData['first_month_max_service_num'];
                    }elseif($month_cancel == 12)
                    {
                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }else
                    {
                        $max_cancel_num = $serviceData['end_month_max_service_num'];
                    }
                }
            }
        }
        return $max_cancel_num;
    }
    
    
    
    //年度保有消费
    public function yearAmount($customerIds,$shop_id,$today)
    {
        $res['md_amount'] = 0;
        $res['mz_amount'] = 0;
        $res['year_amount'] = 0;
        $start_time =  strtotime($today.' -365 day');
        $end_time = strtotime($today);
        
        $telArray = Db::name('customer')->where('id',$customerIds)->column('telephone');
        //查询门诊用户
        $menzhenArray =  Db::name('customer')->alias('c')
            ->join('shop s', 'c.shop_id=s.shop_id', 'LEFT')
            ->where('c.customer_name', 'notlike', '%美团%')
            ->where('c.status', 1)
            ->where('c.telephone', 'in', $telArray)
            ->where('s.shop_type', 1)    
            ->column('c.id');
        if (!is_array($customerIds))
        {
            $customerIds = explode(',', (string)$customerIds);
        }
        $customerIdsArray = array_merge($customerIds,$menzhenArray);
        
        
        
        // 初始化 $md 和 $mz 列表
        $md = [];
        $mz = [];
        // 根据 shop_id 进行分类
        foreach ($customerIdsArray as $id)
        {
            // 查询该客户 ID 对应的 shop_id
            $shopIdOfRelated = Db::name('customer')->where('id', $id)->value('shop_id');
            if ($shopIdOfRelated == $shop_id)
            {
                $md[] = $id;
            } else {
                $mz[] = $id;
            }
        }
        
        // 计算门店收款和退款总和
        $md_sum = Db::name('shop_refund_order')
            ->where([
                ['status', '=', 2], // 已下推
                ['uid', 'in', $md],
                ['deal_time', 'between', [$start_time, $end_time]]
            ])
            ->field([
                // 计算收款金额总和，使用 pay_amount + shop_transfer_amount
                "SUM(CASE WHEN `type` = 3 AND `refund_type` = '101.02' THEN pay_amount + shop_transfer_amount ELSE 0 END) as total_shoukuan",
                // 计算退款金额总和，使用 pay_amount + shop_transfer_amount
                "SUM(CASE WHEN `type` = 1 AND `refund_type` <> '101.03' THEN pay_amount + shop_transfer_amount ELSE 0 END) as total_tuikuan"
            ])
            ->find();
        
        // 使用 bcsub 进行高精度减法运算
        $res['md_amount'] = bcsub($md_sum['total_shoukuan'], $md_sum['total_tuikuan'], 2); // 保留 2 位小数
        
        // 计算门诊收款和退款总和
        $mz_sum = Db::name('shop_refund_order')
            ->where([
                ['status', '=', 2], // 已下推
                ['uid', 'in', $mz],
                ['deal_time', 'between', [$start_time, $end_time]]
            ])
            ->field([
                // 计算收款金额总和，使用 pay_amount + shop_transfer_amount
                "SUM(CASE WHEN `type` = 3 AND `refund_type` = '101.02' THEN pay_amount + shop_transfer_amount ELSE 0 END) as total_shoukuan",
                // 计算退款金额总和，使用 pay_amount + shop_transfer_amount
                "SUM(CASE WHEN `type` = 1 AND `refund_type` <> '101.03' THEN pay_amount + shop_transfer_amount ELSE 0 END) as total_tuikuan"
            ])
            ->find();
        
        // 使用 bcsub 进行高精度减法运算
        $res['mz_amount'] = bcsub($mz_sum['total_shoukuan'], $mz_sum['total_tuikuan'], 2); // 保留 2 位小数
        
        // 使用 bcadd 进行高精度加法运算
        $res['year_amount'] = bcadd($res['md_amount'], $res['mz_amount'], 2); // 保留 2 位小数
        // 输出结果
        return $res;
        
    }
    
    
    protected function getOrderModel()
    {
        return new OrderModel();
    }
}